package com.project1.controller;

import com.google.gson.Gson;
import com.project1.model.bo.AdminLoginBO;
import com.project1.service.AdminService;
import com.project1.service.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 *
 *
 */
@WebServlet( "/api/admin/admin/*")
public class AdminServlet extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //当前servlet处理admin操作，如何知道具体的请求-->url
         //区分不同的url
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/admin", "");
        if("login".equals(action)){
            login(request, response);//登录
        }
    }

    /**
     * 管理员登录
     * 1.浏览器向8084发送请求，请求体中有用户的密码参数（json字符串格式）
     * 2.查询数据库，检查
     * 3.返回结果
     * @param request
     * @param response
     */

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //取出请求参数，不能是request.getParameter(key=value)
        //手动解析json字符串
        //获取请求体
        ServletInputStream inputStream = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream ();
        byte[] bytes = new byte[1024];
        int length = 0;
        while((length = inputStream.read(bytes)) != 1){
            outputStream.write(bytes, 0, length);
        }
        //json字符串-->java对象
        String requetBody = outputStream.toString("utf-8");
        Gson gson = new Gson();
        AdminLoginBO loginBO = gson.fromJson(requetBody, AdminLoginBO.class);
        //System.out.println(loginBO);
        int result = adminService.login(loginBO);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
